<?php

namespace App\Services\MakeProductComment;

use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MakeProductComment
{
	protected $user;
	
	protected $order;
	
	protected $product;
	
	protected $data = [];
	
	public function __construct(Order $order, Product $product, $data = [])
	{
		$this->order = $order;
		$this->user = $order->user;
		$this->product = $product;
		$this->data = $data;
	}
	
	protected function createComment()
	{
		$this->data['user_id'] = $this->user->id;
		return $this->product->comments()->create($this->data);
	}
	
	protected function updateOrder()
	{
		$this->order->update(['has_commented' => true]);
	}
	
	protected function updateProduct()
	{
		$commentCounts = $this->product->comment_count + 1;
		
		$commentFaverCounts = $this->product->comments()->where('is_favor', true)->count();
		
		$commentFaverRate = round($commentFaverCounts / $commentCounts * 100);
		
		$this->product->update([
			'comment_count' => $commentCounts,
			'comment_favor_rate' => $commentFaverRate,
		]);
	}
	
	protected function create()
	{
		$comment = DB::transaction(function () {
			
			$comment = $this->createComment();
			
			Log::debug("new comment: {$comment->id}");
			
			$this->updateOrder();
			
			$this->updateProduct();
			
			return $comment;
		});
		
		return $comment;
	}
	
	public function make()
	{
		return $this->create();
	}
}
